package pkg.drowne.org;

import java.util.List;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

public class locate extends MapActivity {

	private TextView latValue, lonValue;
	private Double latDoubleValue, lonDoubleValue;
	private LocationManager locationManager;
	private LocationListener locationListener;
	private MapView mapView;
	private OverlayManager itemizedoverlay;
	private List<Overlay> mapOverlays;
	private Location bestLocation;
	
	private static final int NEWER_CHECK = 1000 * 5;
	
	 /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(
        WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
        
        // creates the activity
        setContentView(R.layout.locate);
        
        setUpContainers();
                
	    mapOverlays = mapView.getOverlays();
	    Drawable drawable = this.getResources().getDrawable(R.drawable.bluedot);
	    itemizedoverlay = new OverlayManager(drawable);
	              
        locateMe();
    }

	private void setUpContainers() {

		latValue = (TextView) findViewById(R.id.latitude_value);
		lonValue = (TextView) findViewById(R.id.longitude_value);
		mapView = (MapView) findViewById(R.id.mapview);
		mapView.setBuiltInZoomControls(true);
	}

	private void locateMe() {
		
	     // Acquire a reference to the system Location Manager
        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

        // Define a listener that responds to location updates
        locationListener = new LocationListener() {
            public void onLocationChanged(Location location) {
            	
            	if( isBetterLocation(location, bestLocation) ) {
            		
            		// if the new location is the most accurate
            		// set it as the current best location
            		bestLocation = location;
            		
	            	// Called when a new location is found by the GPS location provider
	            	// update the lat and lon local values
	            	latDoubleValue = location.getLatitude()*1E6;
	            	lonDoubleValue = location.getLongitude()*1E6;
	            	// update the text values
	            	latValue.setText(latDoubleValue+"");
	            	lonValue.setText(lonDoubleValue+"");
	            	
	        	  	GeoPoint point = new GeoPoint(latDoubleValue.intValue(), lonDoubleValue.intValue());
	        	  	OverlayItem overlayitem = new OverlayItem(point, "", "");
	        	  	
	        	  	itemizedoverlay.addOverlay(overlayitem);
	        	  	mapOverlays.add(itemizedoverlay);
            	}
            	
            	
                 	
            }

            public void onStatusChanged(String provider, int status, Bundle extras) {}

            public void onProviderEnabled(String provider) {}

            public void onProviderDisabled(String provider) {}
          };

        // Register the listener with the Location Manager to receive location updates
        // from the GPS and the cell towers
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
		
	}

	@Override
	protected boolean isRouteDisplayed() {
		// do not visualize routing information
		return false;
	}
	
	// because of android weird location system
	// the newer location is not always the best
	// so I included some basic logic to check
	// which one is the most accurate location
	protected boolean isBetterLocation(Location location, Location currentBestLocation) {
	    if (currentBestLocation == null) {
	        // A new location is always better than no location
	        return true;
	    }

	    // Check whether the new location fix is newer or older
	    long timeDelta = location.getTime() - currentBestLocation.getTime();
	    boolean isSignificantlyNewer = timeDelta > NEWER_CHECK;
	    boolean isSignificantlyOlder = timeDelta < -NEWER_CHECK;
	    boolean isNewer = timeDelta > 0;

	    // If it's been more than NEWER_CHECK since the current location, use the new location
	    // because the user has likely moved
	    if (isSignificantlyNewer) {
	        return true;
	    // If the new location is more than NEWER_CHECK older, it must be worse
	    } else if (isSignificantlyOlder) {
	        return false;
	    }

	    // Check whether the new location fix is more or less accurate
	    int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
	    boolean isLessAccurate = accuracyDelta > 0;
	    boolean isMoreAccurate = accuracyDelta < 0;
	    boolean isSignificantlyLessAccurate = accuracyDelta > 200;

	    // Check if the old and new location are from the same provider
	    boolean isFromSameProvider = isSameProvider(location.getProvider(),
	            currentBestLocation.getProvider());

	    // Determine location quality using a combination of timeliness and accuracy
	    if (isMoreAccurate) {
	        return true;
	    } else if (isNewer && !isLessAccurate) {
	        return true;
	    } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
	        return true;
	    }
	    return false;
	}

	// Checks whether two providers are the same 
	private boolean isSameProvider(String provider1, String provider2) {
	    if (provider1 == null) {
	      return provider2 == null;
	    }
	    return provider1.equals(provider2);
	}

	public void onPause() {
		// Remove the listener you previously added
		locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
		locationManager.removeUpdates(locationListener);
	
		super.onPause();
	}
	
}
